import { AbstractController, Restful, Router } from "@jingli/restful";
import doc from '@jingli/doc';
import { ParamsNotValidError, CustomerError, NotFoundError, NotPermitError } from "@jingli/error";
import { DB } from '../model';
import { md5, genToken } from "../helper";

@Restful()
export default class AuthController extends AbstractController {
    
    $isValidId(id: string) { 
        return /^\d+$/.test(id);
    }

    @doc('登录')
    @Router('/login', 'POST')
    async login(req, res, next) { 
        let { username, pwd } = req.body;
        let user = await DB.models['User'].findOne({
            where: {
                username
            }
        });
        if (!user) { 
            throw new NotFoundError('用户名');
        }
        if (user.pwd != md5(pwd)) { 
            throw new CustomerError(403, '密码不正确');
        }
        let now = Date.now();
        let str = now.toString(16);
        let token = genToken(username, pwd, str);
        let m = DB.models['Token'].build({ uid: user.id, token: token });
        m = await m.save();
        res.json(this.reply(0, { token: m.token }));
    }

    @doc('注册')
    @Router('/registry', 'POST')
    async registry(req, res, next) { 
        let { username, pwd } = req.body;
        if (!username) { 
            throw new ParamsNotValidError('用户名');
        }
        if (!pwd) { 
            throw new ParamsNotValidError('密码');
        }
        let where = { username}
        let user = await DB.models['User'].findOne({
            where,
        });
        if (user) { 
            throw new CustomerError(502, '用户名已被使用');
        }
        pwd = md5(pwd);
        user = DB.models['User'].build({ username, pwd });
        user = await user.save();
        res.json(this.reply(0, { username: user.username }));
    }

    @doc("检测token是否有效")
    @Router('/pong', 'POST')
    async pong(req, res, next) { 
        let { token } = req.headers;
        res.json(this.reply(0, { token}));
    }
}
